package com.ruoyi.livedemo.mapper;

import com.ruoyi.livedemo.entity.GoalItem;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface GoalItemMapper {

    @Select("SELECT * FROM goal_items WHERE user_id=#{userId} ORDER BY target_date IS NULL, target_date, id")
    List<GoalItem> findByUser(Long userId);

    @Select("SELECT * FROM goal_items WHERE id=#{id} AND user_id=#{userId}")
    GoalItem findByIdAndUser(@Param("id") Long id, @Param("userId") Long userId);

    @Insert("INSERT INTO goal_items (user_id, title, description, target_date, status, progress_ratio, category, cover_path) " +
            "VALUES (#{userId}, #{title}, #{description}, #{targetDate}, #{status}, #{progressRatio}, #{category}, #{coverPath})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(GoalItem goal);

    @Update("UPDATE goal_items SET title=#{title}, description=#{description}, target_date=#{targetDate}, " +
            "status=#{status}, progress_ratio=#{progressRatio}, category=#{category}, cover_path=#{coverPath} WHERE id=#{id} AND user_id=#{userId}")
    int update(GoalItem goal);

    @Delete("DELETE FROM goal_items WHERE id=#{id} AND user_id=#{userId}")
    int delete(@Param("id") Long id, @Param("userId") Long userId);

    @Select({
            "<script>",
            "SELECT * FROM goal_items",
            "WHERE user_id=#{userId}",
            "<if test='status != null and status != \"\"'> AND status=#{status}</if>",
            "<if test='category != null and category != \"\"'> AND category=#{category}</if>",
            "ORDER BY target_date IS NULL, target_date, id",
            "LIMIT #{limit} OFFSET #{offset}",
            "</script>"
    })
    List<GoalItem> findPage(@Param("userId") Long userId,
                            @Param("status") String status,
                            @Param("category") String category,
                            @Param("offset") int offset,
                            @Param("limit") int limit);

    @Select({
            "<script>",
            "SELECT COUNT(1) FROM goal_items",
            "WHERE user_id=#{userId}",
            "<if test='status != null and status != \"\"'> AND status=#{status}</if>",
            "<if test='category != null and category != \"\"'> AND category=#{category}</if>",
            "</script>"
    })
    long count(@Param("userId") Long userId,
               @Param("status") String status,
               @Param("category") String category);
}
